package ru.spies.dbfunctional;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.spies.dbwork.DBWork;
import ru.spies.help.MyLogger;
import ru.spies.pages.CountryExistsPage;
import ru.spies.pages.ErrorPage;

/**
 * Servlet implementation class IsCountryExists
 */
@WebServlet("/IsCountryExists")
public class IsCountryExists extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public IsCountryExists() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String countryName=request.getParameter("paramName");
		String storedProcedure = "{call isCountryExists ( ? ) }";
		PrintWriter out = response.getWriter();
		try {
			Connection con = DBWork.getInstance().getConnection();
			CallableStatement statement = con.prepareCall(storedProcedure);
			statement.setString(1, countryName);
			statement.execute();
			ResultSet result = statement.getResultSet();
			result.next();
			out.print(CountryExistsPage.getInstance(result.getBoolean(1)).getThisPage());
			statement.close();
			con.close();
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException | SQLException e) {
			out.print(ErrorPage.getInstance().getThisPage());
			MyLogger.getInstance().getLog().error(MyLogger.EXCEPTION,e);
		}

	}

}
